from flask_restful import Resource, reqparse
from flask import current_app, jsonify
import werkzeug
import uuid
import oss2
import os

from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

AccessKeyID = os.getenv('AccessKeyID')
AccessKeySecret = os.getenv('AccessKeySecret')
Bucket = os.getenv('Bucket')
Endpoint = os.getenv('Endpoint')

URL_PREFIX = 'https://' + Bucket + '.' + Endpoint + '/'

parser = reqparse.RequestParser()
parser.add_argument(
    'file', type=werkzeug.datastructures.FileStorage, location='files')


class FileService(Resource):
    def post(self):
        args = parser.parse_args()
        current_app.logger.info("args is {}".format(args))
        file = args['file']
        current_app.logger.info("file is {}".format(file.filename))
        _, ext = os.path.splitext(file.filename)
        current_app.logger.info("ext is {}".format(ext))
        random_filename = uuid.uuid4().hex + ext
        auth = oss2.Auth(AccessKeyID, AccessKeySecret)
        bucket = oss2.Bucket(auth, Endpoint, Bucket)
        bucket.put_object(random_filename, file)
        current_app.logger.info(
            "file_url: {}".format(URL_PREFIX + random_filename))
        return jsonify(file_url=URL_PREFIX + random_filename)
